<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="班级编码" prop="classCode">
        <el-input
          v-model="queryParams.classCode"
          placeholder="请输入班级编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="班级名称" prop="className">
        <el-input
          v-model="queryParams.className"
          placeholder="请输入班级名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="班级类别" prop="classCategory">
        <el-select
          v-model="queryParams.classCategory"
          placeholder="请选择班级类别"
          clearable
        >
          <el-option
            v-for="dict in classCategoryOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="班主任教师" prop="teacherNo">
        <el-input
          v-model="queryParams.teacherNo"
          placeholder="请选择班主任教师"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <!-- <el-form-item label="学生人数" prop="studentCount">
        <el-input
          v-model="queryParams.studentCount"
          placeholder="请输入学生人数"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <!-- <el-form-item label="开班日期" prop="startDate">
        <el-date-picker clearable
          v-model="queryParams.startDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择开班日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="结业日期" prop="endDate">
        <el-date-picker clearable
          v-model="queryParams.endDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择结业日期">
        </el-date-picker>
      </el-form-item> -->
      <el-form-item label="是否关班" prop="isClosed">
        <el-select
          v-model="queryParams.isClosed"
          placeholder="请选择是否关班"
          clearable
        >
          <el-option
            v-for="dict in isClosedOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['manage:class:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['manage:class:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['manage:class:remove']"
        >删除</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['manage:class:export']"
        >导出</el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="classList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="班级ID" align="center" prop="classId" /> -->
      <el-table-column label="班级编码" align="center" prop="classCode" />
      <el-table-column label="班级名称" align="center" prop="className" />
      <el-table-column label="班级类别" align="center" prop="classCategoryName" />
      <el-table-column label="班主任工号" align="center" prop="teacherNo" />
      <el-table-column label="班主任姓名" align="center" prop="teacherName" />
      <el-table-column label="学生人数" align="center" prop="studentCount" />
      <el-table-column label="开班日期" align="center" prop="startDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结业日期" align="center" prop="endDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="是否关班" align="center" prop="isClosed" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['manage:class:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['manage:class:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改班级信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="班级编码" prop="classCode">
          <el-input v-model="form.classCode" placeholder="请输入班级编码" />
        </el-form-item>
        <el-form-item label="班级名称" prop="className">
          <el-input v-model="form.className" placeholder="请输入班级名称" />
        </el-form-item>
        <el-form-item label="班级类别" prop="classCategory">
          <el-select
            v-model="form.classCategory"
            placeholder="请选择班级类别"
            clearable
          >
            <el-option
              v-for="dict in classCategoryOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
      <el-form-item label="班主任教师" prop="teacherNo">
        <el-select v-model="form.teacherNo" placeholder="请选择班主任教师" filterable>
          <el-option
            v-for="item in teacherList"
            :key="item.teacherNo"
            :label="item.teacherName + ' (' + item.teacherNo + ')'"
            :value="item.teacherNo"
          ></el-option>
        </el-select>
      </el-form-item>
        <el-form-item label="学生人数" prop="studentCount">
          <el-input v-model="form.studentCount" placeholder="请输入学生人数" />
        </el-form-item>
        <el-form-item label="开班日期" prop="startDate">
          <el-date-picker clearable
            v-model="form.startDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择开班日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结业日期" prop="endDate">
          <el-date-picker clearable
            v-model="form.endDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择结业日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="是否关班" prop="isClosed">
          <el-select
            v-model="form.isClosed"
            placeholder="请选择是否关班"
            clearable
          >
            <el-option
              v-for="dict in isClosedOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <!-- <el-form-item label="逻辑删除标识" prop="delFlag">
          <el-input v-model="form.delFlag" placeholder="请输入逻辑删除标识" />
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listClass, getClass, delClass, addClass, updateClass } from "@/api/manage/class"
import { listTeacher } from "@/api/manage/teacher"
import { getDicts } from "@/api/system/dict/data"

export default {
  name: "Class",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 班级信息表格数据
      classList: [],
      // 教师列表数据
      teacherList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否关班字典
      isClosedOptions: [],
      // 班级类别字典
      classCategoryOptions: [],
      // 当前选中的教师姓名
      teacherName: "",
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        classCode: null,
        className: null,
        classCategory: null,
        teacherNo: null,
        studentCount: null,
        startDate: null,
        endDate: null,
        isClosed: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        classCode: [
          { required: true, message: "班级编码不能为空", trigger: "blur" }
        ],
        className: [
          { required: true, message: "班级名称不能为空", trigger: "blur" }
        ],
        classCategory: [
          { required: true, message: "班级类别不能为空", trigger: "blur" }
        ],
        createTime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" }
        ],
        updateTime: [
          { required: true, message: "更新时间不能为空", trigger: "blur" }
        ],
      }
    }
  },
  created() {
    this.getList()
    this.getTeacherList()
    this.getDicts("yes_or_no").then(response => {
      this.isClosedOptions = response.data
    })
    this.getDicts("class_category").then(response => {
      this.classCategoryOptions = response.data
    })
  },
  methods: {
    /** 查询教师列表 */
    getTeacherList() {
      return listTeacher().then(response => {
        this.teacherList = response.rows
        return response.rows
      })
    },
    /** 查询班级信息列表 */
    getList() {
      this.loading = true
      listClass(this.queryParams).then(response => {
        this.classList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        classId: null,
        classCode: null,
        className: null,
        classCategory: null,
        teacherNo: null,
        teacherName: null,
        studentCount: null,
        startDate: null,
        endDate: null,
        isClosed: null,
        remark: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        delFlag: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.classId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加班级信息"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const classId = row.classId || this.ids
      
      // 确保先加载教师列表，再获取班级数据
      Promise.resolve().then(() => {
        if (this.teacherList.length === 0) {
          return this.getTeacherList()
        }
        return Promise.resolve()
      }).then(() => {
        return getClass(classId)
      }).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改班级信息"
      }).catch(error => {
        console.error('获取班级信息失败:', error)
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.classId != null) {
            updateClass(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addClass(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const classIds = row.classId || this.ids
      this.$modal.confirm('是否确认删除班级信息编号为"' + classIds + '"的数据项？').then(function() {
        return delClass(classIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 处理教师选择变更 */
    // handleTeacherChange(value) {
    //   // 根据选择的教师工号查找对应的教师姓名
    //   const selectedTeacher = this.teacherList.find(item => item.teacherNo === value);
    //   if (selectedTeacher) {
    //     this.form.teacherName = selectedTeacher.teacherName;
    //   }
    // },
    /** 导出按钮操作 */
    handleExport() {
      this.download('manage/class/export', {
        ...this.queryParams
      }, `class_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
